<template>
  <PerfectTableComponent
    :loadTableList="loadTableList"
    :changePageSize="changePageSize"
    :changePage="changePage"
    :removeQueryField="removeQueryField"
    :clearQuery="clearQuery"
    v-model:query="query"
    title="生产订单模块"
    ref="tableRef"
    :showAddNewButton="false"
    :showEditButton="false"
    :showDeleteButton="false"
    :allowEditTableCell="false"
    :queryFormHeaders="queryFormHeaders"
    :table="table"
    :tableColumns="tableColumns"
    :showTableIndex="false"
    :operatorColumnWidth="300"
    :baseUrl="urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDER"
    v-model:multipleSelection="multipleSelection"
  >
    <!--所属车型-->
    <template #table_column_carModelName="scope: any">
      {{ scope.row.carModelConfig.carModel != null ? scope.row.carModelConfig.carModel.name : '' }}
    </template>
    <!--所属车型配置-->
    <template #table_column_carModelConfigName="scope: any">
      {{ scope.row.carModelConfig != null ? scope.row.carModelConfig.name : '' }}
    </template>
    <!-----------------------------表格自定义列（操作列）----------------------------------------->
    <!--所属车型配置-->
    <template #toorbar_left_right>
      <el-button type="primary" icon="Grid" plain @click="generateOrder">生成生产订单</el-button>
      <el-button type="primary" icon="Grid" :disabled="!multipleSelection.length" plain @click="beginProduction">执行生产</el-button>
    </template>
    <template #table_operator_right="scope">
      <el-dropdown placement="bottom-start" @command="handleOrderStatus($event, scope.row)" style="margin-left: 10px; margin-top: 1px">
        <el-button type="primary" size="small" icon="Grid" plain>订单操作</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-if="scope.row.status !== 'planned'" command="simulateProduction">
              {{ scope.row.status == 'in_progress' ? '模拟生产操作' : '查看生产过程' }}
            </el-dropdown-item>
            <template v-if="scope.row.status == 'in_progress'">
              <el-dropdown-item command="paused">暂停生产</el-dropdown-item>
            </template>
            <el-dropdown-item v-if="scope.row.status == 'paused'" command="in_progress">恢复生产</el-dropdown-item>
            <el-dropdown-item v-if="scope.row.status == 'planned'" command="cancelled">取消生产</el-dropdown-item>
            <!-- <el-dropdown-item v-if="scope.row.status == 'completed'" command="a">整车</el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
  </PerfectTableComponent>
  <!--模拟生产对话框-->
  <SimulateProductionDialog ref="simulateProductionDialogRef" />
</template>

<script setup lang="ts">
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import SimulateProductionDialog from '@/views/page/mes/productionorder/SimulateProductionDialog.vue';
import { onMounted, provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import urls from '@/api/request/urls';
import { getDict } from '@/api/dict';
import type { ShopCarOrder } from '@/types/interface/shop_interface';
import Request from '@/api/request/request';
import { ElMessage } from 'element-plus';
import type { ProductionOrder } from '@/types/interface/mes_interface';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDER
);
// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([]);

//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([]);

//表单==========================================================
//表单对象
const form = ref<ShopCarOrder>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([]);
//定义表格复选框。注意非必填字段
const multipleSelection = ref<ProductionOrder[]>([]); // 复选框选择的记录row

onMounted(async () => {
  //定义优先级选项。放在mounted中执行时，要将引用改变量的属性也放进来。
  const productionOrderStatusDict = await getDict('汽车生产订单状态', 'string');
  const isInspectionPassedDict = await getDict('审核状态', 'boolean');
  queryFormHeaders.value = [
    // 查询表单
    {
      prop: 'carModelConfig.id',
      label: '车型配置',
      type: 'selectRemote',
      width: '200px',
      url: urls.API_URL_BACKSTAGE_MES_CARMODELCONFIG,
      queryNameForUrl: 'name',
      config: {
        valueKey: 'id',
        defaultProp: {
          value: 'id',
          label: '{name}'
        }
      }
    },
    {
      prop: 'vin',
      label: '车辆识别码'
    }
  ];
  //表格对象
  tableColumns.value = [
    {
      label: '车型',
      prop: 'carModelName',
      type: 'custom',
      width: 150
    },
    {
      label: '车型配置',
      prop: 'carModelConfigName',
      type: 'custom',
      width: 200
    },
    {
      label: '生产状态',
      prop: 'status',
      width: 100,
      type: 'dict',
      dict: productionOrderStatusDict,
      config: {
        dictTag: {
          primary: ['completed'],
          success: ['in_progress'],
          warning: ['paused'],
          danger: ['cancelled']
        }
      }
    },
    {
      label: '审核结果',
      prop: 'auditResult',
      width: 100,
      type: 'dict',
      dict: isInspectionPassedDict,
      config: {
        dictTag: {
          primary: [true],
          danger: [false]
        }
      }
    },
    // {
    //   label: '生产状态',
    //   prop: 'status',
    //   type: 'dict',
    //   dict: productionOrderStatusDict,
    //   width: 120
    // },
    {
      label: 'vin码',
      prop: 'vin',
      width: 200
    },
    {
      label: '开始生产时间',
      prop: 'startTime',
      width: 180
    },
    {
      label: '完成生产时间',
      prop: 'endTime',
      width: 180
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 180
    },
    {
      label: '最后编辑时间',
      prop: 'updateTime',
      width: 180
    }
  ];
});
//生成生产订单
const generateOrder = async () => {
  const resData: any = await new Request(`${urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDER}/generate`).post();
  if (resData.success) {
    const num = resData.data; //获取生产订单生成的数量
    let message;
    if (num > 0) {
      message = `成功生成${num}个生产订单`;
    } else {
      message = '目前没有生产订单可以生成';
    }
    ElMessage({
      message: message,
      type: 'success'
    });
    loadTableList();
  }
};
// 启动生产订单
const beginProduction = async () => {
  if (multipleSelection.value.length > 0) {
    const ids: string[] = []; // 定义批量操作的角色主键
    for (let i = 0; i < multipleSelection.value.length; i += 1) {
      const item: ProductionOrder = multipleSelection.value[i];
      ids.push(item.id!.toString());
    }
    const resData = await new Request(`${urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDER}/beginProduction`, JSON.stringify(ids)).patch();
    if (resData.success) {
      ElMessage.success('订单开始生产');
      loadTableList(); // 刷新表格
    }
  } else {
    ElMessage.error('请至少选择一条数据');
  }
};
//==============================模拟生产操作====================================================
const simulateProductionDialogRef = ref();
//操作订单下拉框
const handleOrderStatus = async (command: string | number | object, productionOrder: ProductionOrder) => {
  if (command === 'simulateProduction') {
    //如果是模拟生产
    simulateProductionDialogRef.value.openDialog(productionOrder.id);
  } else if (command === 'paused' || command === 'cancelled' || command === 'in_progress') {
    //如果是修改订单状态生产
    const resData: any = await new Request(`${urls.API_URL_BACKSTAGE_MES_PRODUCTIONORDER}/${productionOrder.id}/status`, null, {
      params: { targetStatus: command }
    }).patch();
    if (resData.success) {
      loadTableList();
    }
  }
  // 读取修改订单状态
  // const resData: any = await new Request(`${urls.API_URL_BACKSTAGE_SHOP_CARORDER}/${carOrder.id}/status`, null, {
  //   params: { targetStatus: command }
  // }).patch();
  // if (resData.success) {
  //   loadTableList();
  // }
};
</script>

<style scoped></style>
